
import requests
import logging
from .api_key import ALIYUN_DASHSCOPE_API_KEY

print(ALIYUN_DASHSCOPE_API_KEY)

class CloudModel:
    def __init__(self):
        self.api_key = ALIYUN_DASHSCOPE_API_KEY
        self.api_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"

    def generate(self, prompt: str, max_tokens: int = 128) -> str:
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        payload = {
            "model": "qwen-turbo",
            "input": {
                "messages": [
                    {"role": "user", "content": prompt}
                ]
            },
            "parameters": {
                "max_tokens": max_tokens,
                "temperature": 0.7,
                "top_p": 0.9
            }
        }

        try:
            logging.info(f"请求数据: {payload}")
            response = requests.post(self.api_url, headers=headers, json=payload, timeout=30)
            logging.info(f"响应状态码: {response.status_code}")
            logging.debug(f"响应内容: {response.text}")

            response.raise_for_status()
            data = response.json()

            return data["output"]["text"].strip()

        except requests.exceptions.RequestException as e:
            logging.error(f"阿里云大模型调用失败 (网络问题): {e}", exc_info=True)
            return "[AI摘要] 网络请求失败，请检查API Key或网络连接。"
        except KeyError as e:
            logging.error(f"阿里云大模型返回格式异常: 缺少字段 {e}", exc_info=True)
            return "[AI摘要] 返回内容格式错误，请检查API文档。"
        except Exception as e:
            logging.error(f"阿里云大模型调用失败 (未知错误): {e}", exc_info=True)
            return "[AI摘要] 云端模型调用失败，请稍后再试。"